import React, { useRef, useState, useEffect, useImperativeHandle } from 'react';
import {
    ScrollView,
    Text,
    TouchableOpacity,
    View,
    StyleSheet,
    ScrollViewProps,
    Animated,
    Easing
} from 'react-native';
import { PanGestureHandler } from 'react-native-gesture-handler';

interface TagScrollViewProps extends ScrollViewProps {
    tags: string[]; // 标签数据
    onTagPress?: (index: number) => void; // 标签点击的回调
    activeIndex?: number; // 当前激活的标签索引
}

// 使用 forwardRef 将组件的 ref 传递出去
const TagScrollView = React.forwardRef<TagScrollViewProps, TagScrollViewProps>(
    ({ tags, onTagPress, activeIndex: propActiveIndex = 0, ...scrollViewProps }, ref) => {
        const scrollViewRef = useRef<ScrollView>(null);
        const [activeIndex, setActiveIndex] = useState<number>(propActiveIndex);
        const [tagWidths, setTagWidths] = useState<number[]>([]); // 保存每个标签的宽度
        const [scrollViewWidth, setScrollViewWidth] = useState<number>(0); // ScrollView 宽度

        // Animated values for each tag
        const animations = useRef(tags.map(() => new Animated.Value(0))).current;
        console.log('tags', tags);

        useEffect(() => {
            // 当组件加载时，依次启动每个标签的动画
            tags.forEach((_, index) => {
                Animated.timing(animations[index], {
                    toValue: 1,
                    duration: 500,
                    delay: index * 50, // 每个标签延迟显示
                    easing: Easing.out(Easing.ease),
                    useNativeDriver: true,
                }).start();
            });
        }, [tags]);

        // 当激活某个标签时调用
        const activateTag = (index: number) => {
            setActiveIndex(index);
            onTagPress && onTagPress(index);

            // 计算将点击的标签居中需要滚动的距离
            let offset = 0;
            for (let i = 0; i < index; i++) {
                offset += tagWidths[i] || 0;
            }

            const tagWidth = tagWidths[index] || 0;
            const centerOffset = offset + tagWidth / 2 - scrollViewWidth / 2;

            // 滚动到选中的标签位置，并居中
            if (scrollViewRef.current) {
                scrollViewRef.current.scrollTo({ x: centerOffset > 0 ? centerOffset : 0, animated: true });
            }
        };

        // 使用 useImperativeHandle 来暴露给父组件
        useImperativeHandle(ref, () => ({
            activateTag, // 这里暴露了 activateTag 方法
        }));

        // 保存每个标签的宽度
        const handleTagLayout = (index: number, width: number) => {
            const newWidths = [...tagWidths];
            newWidths[index] = width;
            setTagWidths(newWidths);
        };

        return (
            <View style={styles.container}>

                <PanGestureHandler
                    onGestureEvent={(event) => {
                        // 仅允许水平滑动 ScrollView，不让它影响 TabView 的切换
                        if (Math.abs(event.nativeEvent.translationX) > Math.abs(event.nativeEvent.translationY)) {
                            // 横向滑动逻辑
                        }
                    }}
                >
                    <ScrollView
                        horizontal
                        ref={scrollViewRef}
                        showsHorizontalScrollIndicator={false}
                        contentContainerStyle={styles.scrollContainer}
                        onLayout={(event) => {
                            // 获取 ScrollView 的宽度
                            setScrollViewWidth(event.nativeEvent.layout.width);
                        }}
                        nestedScrollEnabled={true}
                        {...scrollViewProps}

                    >
                        {
                            tags.map((tag, index) => {
                                const animatedStyle = {
                                    opacity: animations[index],
                                    transform: [
                                        {
                                            translateX: animations[index]?.interpolate({
                                                inputRange: [0, 1],
                                                outputRange: [50, 0], // 从右向左移动
                                            }),
                                        },
                                    ],
                                };

                                return (
                                    <Animated.View
                                        key={index}
                                        style={[animatedStyle]}
                                        onLayout={(event) => handleTagLayout(index, event.nativeEvent.layout.width)} // 获取标签的宽度
                                    >
                                        <TouchableOpacity
                                            style={[styles.tag, activeIndex === index && styles.activeTag]}
                                            onPress={() => activateTag(index)}
                                        >
                                            <Text style={[styles.tagText, activeIndex === index && styles.activeTagText]}>
                                                {tag?.label}
                                            </Text>
                                        </TouchableOpacity>
                                    </Animated.View>
                                );
                            })
                        }
                    </ScrollView>
                </PanGestureHandler>


            </View>
        );
    }
);

const styles = StyleSheet.create({
    container: {
        // paddingVertical: 10,
    },
    scrollContainer: {
        flexDirection: "row",
        alignItems: "center",
    },
    tag: {
        paddingHorizontal: 15,
        paddingVertical: 8,
        // marginRight: 28,
    },
    activeTag: {},
    tagText: {
        color: '#676978',
        fontSize: 14,
        fontWeight: "400",
    },
    activeTagText: {
        color: '#EC6138', // 激活状态的文字颜色
        fontWeight: "bold",
    },
});

export default TagScrollView;
